<?php
defined('IN_SEC') or exit('Access Denied.');
/*--[SFUNCTION A]--*/
function avatar($avatar = ''){
	return $avatar ? $avatar : '/static/ace/assets/avatars/user.jpg';
}
/*--[SFUNCTION B]--*/
/*--[SFUNCTION C]--*/
function conf($conf = '', $key = ''){
	global $_G;
	if ( $_G['config'][$conf] ){
		if ( $key ){
			if($_G['config'][$conf][$key] ){
				return $_G['config'][$conf][$key];
			}else{
				return false;
			}
		}
		return $_G['config'][$conf];
	}
	$file = APP_PATH . '/include/configs/' . $path . '/' . $conf . '.conf.php';
	if ( file_exists($file) ){
		$_G['config'][$conf] = include $file;
	}else{
		$_G['config'][$conf] = false;
	}
	return $key && $_G['config'][$conf] ? $_G['config'][$conf][$key] : $_G['config'][$conf];
}
function cookieset($k = '', $v = '', $expire = 0) {
	$pre = substr(md5($_SERVER['HTTP_HOST']), 0, 4);
	$k = "{$pre}_{$k}";
	if ( $expire==0 ) {
		$expire = time() + 365 * 86400;
	} else {
		$expire += time();
	}
	setCookie($k, $v, $expire, '/');
}

function cookieadd($k, $v, $max = 0){
	if ( $cookie = cookieget($k) ){
		$cookie = json_decode($cookie, true);
		if ( is_array($cookie) ){
			if ( $max ){
				$data = array_slice($cookie, 0, ($max - 1 ), true);
			}else{
				$data = $cookie;
			}
			$cookie = cookieexp($v);
			$cookie = ($cookie + $data);
		}else{
			return false;
		}
	}else{
		$cookie = cookieexp($v);
	}
	$cookie = json_encode($cookie);
	cookieset($k, $cookie, 0);
}

function cookieexp($v = ''){
	$cookie = array();
	if ( is_array($v) ){
		$cookie[$v[0]] = $v[1];
	}else{
		$cookie = array(
			$v => $v
		);
	}
	return $cookie;
}

function cookieget($k, $default = '') {
	$pre = substr(md5($_SERVER['HTTP_HOST']), 0, 4);
	$k = "{$pre}_{$k}";
	return isset($_COOKIE[$k]) ? strval($_COOKIE[$k]) : $default;
}
/*--[SFUNCTION D]--*/
function dhtmlspecialchars($string = array()){
	if ( is_string($string) ){
		$string = htmlspecialchars($string);
	}else if( is_array($string) ){
		foreach( $string as $key => $one ){
			$string[$key] = dhtmlspecialchars($one);
		}
	}
	return $string;
}
function daddslashes($string = array()){
	if ( is_string($string) ){
		$string = addslashes($string);
	}else if( is_array($string) ){
		foreach( $string as $key => $one ){
			$string[$key] = daddslashes($one);
		}
	}
	return $string;
}
function dstripslashes($string = array()) {
	if(is_array($string)) {
		foreach($string as $k => $v) {
			$string[$k] = dstripslashes($v);
		}
	} else {
		$string = stripslashes($string);
	}
	return $string;
}
function debuginfo() {
	$cache = conf('cache');
	return array(
	    'time' => number_format((microtime(true) - SEC_SYS_LOAD_TIME), 6),
	    'queries' => DB::$count,
		'cache' => $cache['memcache'] ? 'Memcached' : 'Supcache',
    );
}
function dmkdir($dir){
	$father = dirname($dir);
	if( !is_dir($father) ){
		dmkdir($father, 0777);
		mkdir($dir, 0777);
	}else{
		mkdir($dir, 0777);
	}
}
function delete($table = '', $id = 0, $key = 'id'){
	$where = is_array($id) ? $id : array($key => $id);
	return DB::Delete($table, $where);
}
function delcache($cachekey = ''){
	return Cache::Del($cachekey);
}
function dialog($template = '', $html = ''){
	$template = (strpos($template, 'admin_') === 0) ? ($template . '_dialog') : ((strpos($template, 'ajax/') === 0) ? $template : 'ajax/' . $template);
	$html = $html ? $html : render($template);
	jsonp($html, 'dialog');
}
/*--[SFUNCTION E]--*/
/*--[SFUNCTION F]--*/
function fetch($table, $id = 0, $key = 'id', $cachekey = '', $cachetime = 3600){
	$where = is_array($id) ? $id : array($key => $id);
	$options = array(
		'cachekey' => $cachekey,
		'cachetime' => $cachetime,
	);
	return DB::Fetch($table, $where, $options);
}
function formhash($hash = ''){
	global $_G;
	$admincp = defined('IN_ADMINCP') ? 'Only For Dwshop Admin Control Panel' : '';
	return substr(md5(substr(SYS_TIME, 0, -7) . $_G['user']['username'] . $admincp . $hash), 8, 8);
}
function flushcache(){
	return Cache::Flush();
}
/*--[SFUNCTION G]--*/
function get($params = array(), $value = array(), $pre = ''){
	$data = array();
	$params = is_array($params) ? $params : explode(',', trim($params, ','));
	$value = $value ? $value : array_merge($_GET, $_POST);
	if ( is_array($params) && is_array($value) ){
		foreach($value as $key => $one ){
			if ( in_array($key, $params) ){
				$data[$pre.$key] = $one;
			}
		}
	}
	return $data;
}
function getcache($cachekey = ''){
	return Cache::Get($cachekey);
}
function get_client_ip() {
	$ip = $_SERVER['REMOTE_ADDR'];
	if (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
		$ip = $_SERVER['HTTP_CLIENT_IP'];
	} elseif(isset($_SERVER['HTTP_X_FORWARDED_FOR']) AND preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
		foreach ($matches[0] AS $xip) {
			if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
				$ip = $xip;
				break;
			}
		}
	}
	return $ip;
}
/*--[SFUNCTION H]--*/
/*--[SFUNCTION I]--*/
function is_get(){
	return isset($_GET) && $_SERVER['REQUEST_METHOD'] == 'GET';
}
function is_post($notemplate = true){
	$post = isset($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST';
	$post && $notemplate && !defined('NOTEMPLATE') ? define('NOTEMPLATE', $notemplate) : '';
	return $post;
}
function idserialize($ids = array(), $key = 'id', $join = '\',\''){
	if ( is_array($ids) ){
		$idstring = array();
		foreach( $ids as $k => $v ){
			if ( $v[$key] ){
				$idstring[$v[$key]] = $v[$key];
			}
		}
	}else{
		$idstring = explode(',', trim($ids));
	}
	return join($join, $idstring);
}

function idserializes($ids = array(), $key = 'id', $join = '\',\''){
	$multi = strpos($key, ',') ? 1 : 0;
	if ( is_array($ids) ){
		$idstring = array();
		$multi_key = explode(',', trim($key, ','));
		foreach( $ids as $k => $v ){
			foreach( $multi_key as $multik => $multiv ){
				$multiv = trim($multiv);
				if ( $multiv && $v[$multiv] ){
					$idstring[$multiv][$v[$multiv]] = $v[$multiv];
				}
			}
		}
	}else{
		return null;
	}
	foreach( $idstring as $k => $v ){
		$idstring[$k] = join($join, $v);
	}
	return $multi ? $idstring : current($idstring);
}


function is_email($email = '') {
	return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
function is_mobile($mobile = '', $only = false) {
	return $only ? preg_match('/^1[3458][\d]{9}$/', $mobile) : (preg_match('/^1[3458][\d]{9}$/', $mobile) || preg_match('/^[569][\d]{7}$/', $mobile));
}
/*--[SFUNCTION J]--*/
function json($data = array()){
	exit(json_encode($data));
}
function jsonp($data = '', $type = 'alert', $error = 0){
	$data = is_array($data) ? $data : array(
		'data' => $data
	);
	if ( $type == 'data' ){
		$data = array(
			'data' => $data,
		);
	}
	$data['data'] = $data['data'] ? $data['data'] : null;
	$data['type'] = $data['type'] ? $data['type'] : $type;
	$data['error'] = $data['error'] ? $data['error'] : $error;
	json($data);
}
/*--[SFUNCTION K]--*/
/*--[SFUNCTION L]--*/
function limitquery($table, $where = array(), $options = array(), $offset = null, $size = null){
	if ( !is_null($offset) && !is_null($size) ){
		$options['offset'] = $offset;
		$options['size'] = $size;
	}
	return DB::Limit($table, $where, $options);
}
function limitcache($table, $cachekey = '', $cachetime = 3600, $where = array(), $options = array()){
	$opt = array(
		'cachekey' => $cachekey,
		'cachetime' => $cachetime,
	);
	$options = array_merge($options, $opt);
	return limitquery($table, $where, $options);
}
/*--[SFUNCTION M]--*/
/*--[SFUNCTION N]--*/
function need_ajax(){
	if ( !AJAX ){
		$bug = new Bug;
		$bug->system('The page is need use ajax to access.');
	}
}
/*--[SFUNCTION O]--*/

function option($a = array(), $v = '', $all = null){
	$option = null;
	if ( $all ){
		$selected = ($v) ? null : 'selected';
		$option .= "<option value='-1' $selected>" . strip_tags($all) . "</option>";
	}

	$v = explode(',', $v);
	settype($v, 'array');
	foreach( $a as $key => $value ){
		if (is_array($value)) { 
			$key = strval($value['id']);
			$value = strval($value['name']); 
		}
		$selected = in_array($key, $v) ? 'selected' : null;
		$option .= "<option value='{$key}' {$selected}>" . strip_tags($value) . "</option>";
	}

	return $option;
}
function output_hook($c = '') {
	$HTTP_ACCEPT_ENCODING = $_SERVER["HTTP_ACCEPT_ENCODING"]; 

	if( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false ){
		$encoding = 'x-gzip'; 
	}else if( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ){
		$encoding = 'gzip';
	}else {
		$encoding == false;
	}
	if ( function_exists('gzencode') && $encoding) {
		//$c = gzencode($c);
		header("Content-Encoding: {$encoding}"); 
	}
	$length = strlen($c);
	header("Content-Length: {$length}");
	die($c);
}

/*--[SFUNCTION P]--*/
function pages($amount = 1, $pagesize = 20){
	if ( function_exists('my_app_pages') ){
		return my_app_pages($amount, $pagesize);
	}
	$pagesize = $pagesize ? $pagesize : 20;
	$page = new Pager();
	return $page->init($amount, $pagesize);
}
function parse_array($data = array(), $key = 'id'){
	if ( !$data ){
		return array();
	}
	$datas = array();
	foreach( $data as $k => $v ){
		unset($data[$k]);
		$datas[$v[$key]] = $v;
	}
	return $datas;
}
/*--[SFUNCTION Q]--*/
/*--[SFUNCTION R]--*/
function redirect($url = ''){
	$url = $url ? $url : (HTTP_REFERER ? HTTP_REFERER : APP_URL);
	if( AJAX ){
		jsonp($url, 'redirect');
	}
	header("Location:{$url}");
	exit;
}
function refresh($url = ''){
	$url = $url ? $url : REQUEST_URI;
	if ( AJAX ){
		jsonp($url, 'refresh');
	}else{
		redirect($url);
	}
}
function render($template) {
	ob_start();
    foreach($GLOBALS as $k => $v) {
        ${$k} = $v;
    }
	include template($template, true);
	return render_hook(ob_get_clean());
}

function render_hook($c = '') {
	return $c;
}

function random($len = 6, $numer = true){
	$secret = '';
	for ($i = 0; $i < $len;  $i++) {
		if ( $numer ){
			if (0==$i) {
				$secret .= chr(rand(49, 57));
			} else {
				$secret .= chr(rand(48, 57));
			}
		}else if ( !$numer ){
			$secret .= chr(rand(65, 90));
		}else{
			if ( 0==$i ){
				$secret .= chr(rand(65, 90));
			} else {
				$secret .= (0==rand(0,1)) ? chr(rand(65, 90)) : chr(rand(48,57));
			}
		}
	}
	return $secret;
}
/*--[SFUNCTION S]--*/
function saveconfig($conf, $mixed = '', $allow = '', $data = array()){
	$data = $data ? $data : $_POST;
	$file = APP_PATH . '/include/configs/' . $conf . '.conf.php';
	if ( $mixed ){
		$allow = $allow ? $allow . ',' . $mixed : $mixed;
		$mixed = explode(',', $mixed);
		foreach( $mixed as $k => $v ){
			if ( $v ){
				if ( !$data[$v] ){
					return false;
				}
			}
		}
	}
	if ( $allow ){
		$allow = explode(',', $allow);
		foreach( $data as $k => $v ){
			if ( !in_array($k, $allow) ){
				unset($data[$k]);
			}
		}
	}
	$data = dhtmlspecialchars($data);
	if ( !is_dir(dirname($file)) ){
		dmkdir(dirname($file));
	}
	return write($file, $data);
}
function setcache($cachekey = '', $data = array(), $expire = 3600, $flag = 0){
	return Cache::Set($cachekey, $data, $flag, $expire);
}

/* phpcms */
function str_cut($string, $length, $dot = '...') {
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '"', '"', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8') {
		$length = intval($length-strlen($dot)-$length/3);
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
		$strcut = str_replace(array('∵', '&', '"', "'", '"', '"', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	} else {
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		$current_str = '';
		$search_arr = array('&',' ', '"', "'", '"', '"', '—', '<', '>', '·', '…','∵');
		$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
		$search_flip = array_flip($search_arr);
		for ($i = 0; $i < $maxi; $i++) {
			$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			if (in_array($current_str, $search_arr)) {
				$key = $search_flip[$current_str];
				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
			}
			$strcut .= $current_str;
		}
	}
	return $strcut.$dot;
}
/*--[SFUNCTION T]--*/
function template($template = '', $inajax = false){
	$tmpname = $template;
	$setting = conf('template');
	$skin = (strpos($template, 'admin_') === 0) ? 'admin' : ($setting['theme'] ? $setting['theme'] : 'default');
	$template = $skin . '/' . (AJAX && !$inajax ? 'ajax/' : '') . $template;
	if( AJAX && !$inajax ){
		//dialog($tmpname);
	}
	return __template($template);
}
/*--[SFUNCTION U]--*/

function dupload($input = '', $type = 'files', $image = '', $name = 0){
	global $_G;
	$year = date('Y');
	$day = date('md');
	$d = $_FILES[$input];
	$allow = 'jpg,jpeg,gif,png,txt,doc,ppt';//上传扩展名
	$fileinfo = pathinfo($d['name']);
	$filesize = $d['size'];
	$extension = strtolower($fileinfo['extension']);
	$n = ($name ? date('YmdHis') . '-' . $d['name'] : (time().rand(1000,9999)).'.'.$extension);
	if( !$d || $d['error'] != 0 ){
		return -1098;
	}
	if( !preg_match('/'.str_replace(',', '|', $allow).'/i', $extension) ){
		return -1064;
	}
	$image = $image ? $image : "dupload/{$type}/{$year}/{$day}/";
	$image = strpos($image, '.') ? $image : $image.$n;
	$path = APP_PATH . '/static/'. $image;
	if ( !is_dir(dirname($path)) ){
		dmkdir(dirname($path));
	}
	if ( is_resource($d['tmp_name']) ) {
		$data = fread($d['tmp_name'], $filesize);
		file_put_contents($path, $data);
		fclose($d['tmp_name']);
	} else {
		$path = iconv("UTF-8", "gb2312", $path);
		move_uploaded_file($d['tmp_name'], $path);
		@unlink($d['tmp_name']);
	}
	if (is_resource($d['tmp_name'])) {
		fclose($d['tmp_name']);
	}else {
		@unlink($d['tmp_name']);
	}
	return '/static/' . $image;
}

function upload_image($input, $type = 'team', $image = null, $scale = false, $cwidth = 165, $cheight = 165, $watermark = false) {
	global $_G;
	$year = date('Y');
	$day = date('md');
	$n = time().rand(1000,9999).'.jpg';
	$d = $_FILES[$input];
	$allow = 'jpg,jpeg,gif,png';//上传扩展名
	//if ($d && strpos($d['type'], 'image') === 0 && $d['error'] == 0){
	$fileinfo = pathinfo($d['name']);
	$filesize = $d['size'];
	$extension = strtolower($fileinfo['extension']);

	if ($d && (preg_match('/'.str_replace(',', '|', $allow).'/i', $extension)) && $d['error'] == 0){
		$image = $image ? $image : "dupload/{$type}/{$year}/{$day}/";
		$image = strpos($image, '.') ? $image : $image.$n;
		$path = APP_PATH . '/static/'. $image;
		if ( !is_dir(dirname($path)) ){
			dmkdir(dirname($path));
		}
		//Image::Convert($z['tmp_name'], $path, 48, 48, Image::MODE_CUT);
		if ( is_resource($d['tmp_name']) ) {
			$data = fread($d['tmp_name'], $filesize);
			file_put_contents($path, $data);
			fclose($d['tmp_name']);
		} else {
			$path = iconv("UTF-8","gb2312", $path);
			move_uploaded_file($d['tmp_name'], $path);
			@unlink($d['tmp_name']);
		}

		if (is_resource($d['tmp_name'])) {
			fclose($d['tmp_name']);
		}else {
			@unlink($d['tmp_name']);
		}
	}else{
		return '上传失败！';
	}
	return 'http://' . $_SERVER['HTTP_HOST'] . '/static/' . $image;
}

function update($table, $id, $update = array(), $key = 'id'){
	$where = is_array($id) ? $id : array($key => $id);
	return DB::Update($table, $update, $where);
}
function updatecache($table, $id = 0, $update = array(), $cachekey = '', $key = 'id'){
	$update = update($table, $id, $update, $key);
	if ( $update && $cachekey ){
		return delcache($cachekey);
	}else{
		return $update;
	}
}
/*--[SFUNCTION V]--*/
/*--[SFUNCTION W]--*/
function write($path, $data = array()){
	$data = "<?php\nreturn " . var_export($data, true) . ";\n?>";
	return file_put_contents($path, $data);
}
/*--[SFUNCTION X]--*/
/*--[SFUNCTION Y]--*/
/*--[SFUNCTION Z]--*/
?>